package com.yc.login.dao;

import cn.hutool.crypto.digest.DigestUtil;
import com.yc.login.bean.LoginProperties;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class LoginDao {

    @Resource
    private JdbcTemplate jdbc;

    @Resource
    private LoginProperties loginProperties;

    public List<?> login(String username, String password) {
        String sql = "select * from %s where %s=? and %s=?";
        sql = String.format(sql,
                loginProperties.getTableName(),
                loginProperties.getUsernameClumn(),
                loginProperties.getPasswordClumn());
        String userClass = loginProperties.getUserClass();
        Class<?> cls;
        try {
            cls = Class.forName(userClass);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("用户类错误" + userClass, e);
        }
//        String p = DigestUtil.md5Hex(password);
//        System.out.println(p);
        return jdbc.query(sql, new BeanPropertyRowMapper<Object>((Class<Object>) cls) {
        }, username, password);
        //return jdbc.queryForList(sql,username,password);
    }

    public void updatePwd(String username, String password, String newPassword) {
        String sql = "update %s set %s=? where %s=? and %s=?";
        sql = String.format(sql,
                loginProperties.getTableName(),
                loginProperties.getPasswordClumn(),
                loginProperties.getUsernameClumn(),
                loginProperties.getPasswordClumn());
        jdbc.update(sql, newPassword, username, password);
    }

    public void updatePwd(String username, String newPassword) {
        String sql = "update %s set %s=? where %s=?";
        sql = String.format(sql,
                loginProperties.getTableName(),
                loginProperties.getPasswordClumn(),
                loginProperties.getUsernameClumn());
        jdbc.update(sql, newPassword, username);
    }

    public String selectEmailByUsername(String username) {
        String sql = "select %s from %s where %s=?";
        sql = String.format(sql,
                loginProperties.getEmailClumn(),
                loginProperties.getTableName(),
                loginProperties.getUsernameClumn());
        String email = jdbc.queryForObject(sql, String.class, username);
        return email;
    }
}
